package com.jarveis.frame.io;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * 七牛云存储传输
 * 
 * @author liuguojun
 */
public class QiniuTransfer implements NetTransfer {

	private static final Logger logger = Logger.getLogger(QiniuTransfer.class);

	// 设置好账号的ACCESS_KEY和SECRET_KEY
	private String bucketName = null;
	private String bucketHost = null;
	// 密钥配置
	private Auth auth = null;
	private UploadManager uploadManager = null;

	public QiniuTransfer(String ACCESS_KEY, String SECRET_KEY,
			String bucketName, String bucketHost) {
		auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		this.bucketName = bucketName;
		this.bucketHost = bucketHost;
	}

	/**
	 * 连接到服务器
	 * 
	 * @return
	 * @throws Exception
	 */
	public boolean connect() throws Exception {

		return true;
	}

	/**
	 * 断开与服务器的连接
	 * 
	 * @throws Exception
	 */
	public boolean disconnect() throws Exception {

		return true;
	}

	public boolean download(String remote, String local) throws Exception {
		return false;
	}

	public byte[] download(String remote) throws Exception {
		// 构造私有空间需要生成的下载的链接
		String link = auth.privateDownloadUrl(bucketHost + remote, 3600);
		HttpUtil httpUtil = new HttpUtil(link, HttpUtil.HttpMethod.GET);
		if (httpUtil.doRequest()) {
			return httpUtil.getRespData();
		}
		return null;
	}

	public boolean upload(String local, String remote) throws Exception {
		byte[] bytes = FileUtils.readFileToByteArray(new File(local));

		return this.upload(bytes, remote);
	}

	public boolean upload(byte[] bytes, String remote) throws Exception {
		try {
			this.uploadManager = new UploadManager();
			// 调用put方法上传，这里指定的key和上传策略中的key要一致
			Response res = uploadManager.put(bytes, remote, getUpToken(remote));
			// 打印返回的信息
			logger.info(res.bodyString());

			return true;
		} catch (QiniuException e) {
			Response r = e.response;
			try {
				// 响应的文本信息
				logger.info(r.bodyString());
			} catch (QiniuException e1) {
				logger.error(e1.getMessage(), e1);
			}

			return false;
		}
	}

	public boolean remove(String remote) throws Exception {
		try {
			BucketManager bucketManager = new BucketManager(auth);
			bucketManager.delete(bucketName, remote);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
		return false;
	}

	// 覆盖上传
	private String getUpToken(String key) {
		return auth.uploadToken(bucketName, key);
	}

	public boolean CreateDirecroty(String remote) throws Exception {

		return true;
	}

}
